import React, {
    useEffect,
    useLayoutEffect,
    useState,
    useCallback
} from "react";
import { connect, useDispatch } from "react-redux";
import $ from "jquery";
import { message, Popover } from "antd";
import { getQueryVariable, removeToken } from "../../util";
import styled from '@emotion/styled'
import CONFIG from "../../util/config";
import MessageLogo from '../../images/syslogo.png'
import MessageSetLogo from '../../images/syslogo2.png'
import "./index.scss";
import axiosMethod from "../../util/axios";
import {
    lgAlert, LgSplitLine, LgDropdown, LgTopBarContainer, BackToOfficialBlock,
    IdentityBlock,
    LogoutBlock,
    MessageBlock,
    UserBlock, SystemInfo, createClassName, SystemInfoProps
} from "lancoo-web-ui";

const { classNames } = createClassName("lg-top-bar")

const { basicProxy, originUrl, helpAddr, downloadAddr } = CONFIG;

function Header(props) {
    let {
        userInfo,
        sysAddrInfo,
        sysInfo,
        currentIdentity,
        isEdu = false
    } = props;

    let currentIdentity2 = JSON.parse(sessionStorage.getItem('currentIdentity'))
    console.log(currentIdentity2)
    const dispatch = useDispatch();
    const goHome = useCallback(() => {
        let officeSysId = "260"
        let officeUrl = `html/index/?lg_tk=${sessionStorage.getItem("token")}`

        if (isEdu) {
            officeSysId = '264'
            officeUrl = `homepage/web/index.html?lg_tk=${sessionStorage.getItem("token")}`
        }
        if (window.getWebAddr && typeof window.getWebAddr === 'function') {
            window.getWebAddr(officeSysId, function (webAddr) {
                if (!webAddr) {
                    message.warn("暂未部署办公平台，请联系管理员处理！");
                } else {
                    window.open(webAddr + officeUrl)
                }
            })
        } else {
            axiosMethod({
                type: "get",
                url: "/api/commons/system/getServerInfo",
                body: {
                    sysIds: officeSysId
                },
                callback: function (res) {
                    if (!res[0].webSvrAddr) {
                        message.warn("暂未部署办公平台，请联系管理员处理！");
                    } else {
                        window.open(res[0].webSvrAddr + officeUrl)
                    }
                }
            })
        }
    }, [sysAddrInfo, currentIdentity]);

    const goHelp = useCallback(() => {
        let token = sessionStorage.getItem("token") || getQueryVariable("lg_tk");
        window.open(`${helpAddr}?lg_tk=${token}${currentIdentity.identityCode ? "&lg_ic=" + currentIdentity.identityCode : ""}`);
    }, [helpAddr, currentIdentity]);

    const goPerson = useCallback(() => {
        let token = sessionStorage.getItem("token") || getQueryVariable("lg_tk");
        let personUrl = sessionStorage.getItem("baseUrl") + '/html/personalMgr?lg_tk=' + token

        // if (isEdu) {
        //     personUrl = sessionStorage.getItem("baseUrl") +'/UserMgr/PersonalMgr/Default.aspx?lg_tk=' + token
        // }

        window.open(personUrl, '_blank');
    }, []);
    const quitMethod = useCallback(() => {  //退出登录
        // let alert = lgAlert.show({
        //     duration: 0,
        //     content: '是否退出登录？',
        //     isShowCloseBtn: true,
        //     tipType: 'question',
        //     tipSize: 'big',
        //     position:{
        //         xAxis:'50%',
        //         yAxis:'50%',
        //         xOffset: '-50%',
        //         yOffset: '-50%'
        //     },
        //     tipMouldType: 'A',
        //     confirmText: "确认",
        //     closeText: "再想想",
        //     onConfirm: () => {
        //         $.ajax({
        //             url:
        //                 sessionStorage.getItem("baseUrl") +
        //                 "/UserMgr/Login/Api/Login.ashx?token=" +
        //                 sessionStorage.getItem("token") +
        //                 "&method=Logout&params=210",
        //             type: "GET",
        //             dataType: "jsonp",
        //             jsonp: "jsoncallback", //这里的值需要和回调函数名一样
        //             success: function (data) {
        //                 let str = removeToken(window.location.href);
        //                 sessionStorage.removeItem("token");
        //                 localStorage.removeItem("token");
        //                 window.location.href = sessionStorage.getItem('baseUrl') + '/login.html?lg_sysid=200&lg_preurl=' + encodeURI(str)
        //             }
        //         });
        //         lgAlert.close(alert.index)
        //         return
        //     }
        // });
        dispatch({
            type: "SET_ALERTINFO",
            data: {
                visible: true,
                title: "确定要退出登录吗？",
                onCancel: function () {
                    dispatch({
                        type: "SET_ALERTINFO",
                        data: {}
                    })
                },
                onOk: function () {
                    axiosMethod({
                        url: '/api/commons/users/logout',
                        body: {
                            token: sessionStorage.getItem('token'),
                            userId: userInfo.UserID
                        },
                        callback: function (data) {
                            let str = removeToken(window.location.href);
                            sessionStorage.removeItem("token");
                            localStorage.removeItem("token");
                            if (window.location.href?.indexOf('#/setting') > -1) {
                                str = ''
                            }

                            let messageId = '210'
                            if (isEdu) {
                                messageId = '211'
                            }

                            window.location.href = sessionStorage.getItem('baseUrl') + '/login.html?lg_sysid=' + messageId + '&lg_preurl=' + encodeURI(str)
                        }
                    });
                }
            }
        });

        // axiosMethod({
        //     type: "get",
        //     url: sessionStorage.getItem("baseUrl") + "/UserMgr/Login/Api/Login.ashx?token=" + sessionStorage.getItem("token") + "&method=Logout&params=200",
        //     body: {},
        //     callback: function(res){ 

        //     }
        // });
    }, []);
    const showMessage = useCallback(() => {
        $("#Assistant_infoCenter").click();
    }, []);
    const loadScriptOrCss = useCallback((urlArr, num) => {//同步引入动态js和css函数
        if (!num) {
            num = urlArr.length;
        }
        //正则判断是否是css;
        var reg = RegExp(/.css/);
        var scriptOrCss

        if (reg.test(urlArr[num - 1])) {
            // 动态生成css
            scriptOrCss = document.createElement('link');
            scriptOrCss.type = 'text/css';
            scriptOrCss.async = 'async';
            scriptOrCss.href = urlArr[num - 1];
            scriptOrCss.rel = "stylesheet";
            document.getElementsByTagName("head")[0].appendChild(scriptOrCss);

        } else {
            // 动态生成js
            scriptOrCss = document.createElement('script');
            scriptOrCss.type = 'text/javascript';
            scriptOrCss.async = 'async';
            scriptOrCss.src = urlArr[num - 1];
            document.body.appendChild(scriptOrCss);
        }
        if (scriptOrCss.readyState) {
            //IE下
            scriptOrCss.onreadystatechange = function () {
                if (scriptOrCss.readyState == 'complete' || scriptOrCss.readyState == 'loaded') {
                    scriptOrCss.onreadystatechange = null;
                    num--;
                    if (num == 0) {
                    } else {
                        loadScriptOrCss(urlArr, num);
                    }
                }
            }
        } else {
            //其他浏览器
            scriptOrCss.onload = function () {
                num--;
                if (num == 0) {

                } else {
                    loadScriptOrCss(urlArr, num);
                }
            }
        }
    }, []);
    useEffect(() => { //导入消息中心小铃铛
        // window.getWebAddr("210", function (webAddr) {
        //     sessionStorage.setItem('PsnMgrToken', sessionStorage.getItem("token"));//用户Token
        //     sessionStorage.setItem('PsnMgrMainServerAddr', sessionStorage.getItem("baseUrl")); //基础平台IP地址和端口号 形如：http://192.168.129.1:30103/
        //     sessionStorage.setItem('PsnMgrLgAssistantAddr', webAddr); //个人信息管理系统Web站点IP地址和端口号 形如：http://192.168.129.1:10103/
        //     let messageUrl = webAddr
        //     let arr = [messageUrl + '/PsnMgr/LgAssistant/js/jquery-1.7.2.min.js',
        //     messageUrl + "/PsnMgr/LgAssistant/assets/jquery.pagination.js",
        //     messageUrl + "/PsnMgr/LgAssistant/js/lancoo.cp.assistantInfoCenter.js",
        //     messageUrl + "/PsnMgr/LgAssistant/css/lancoo.cp.assistantInfoCenter.css"
        //     ].reverse();
        //     loadScriptOrCss(arr);
        // })
    }, []);

    const systemInfo = {
        type: 'A',
        logoUrl: props.isSetting?MessageSetLogo:MessageLogo,
        systemName: props.title || '消息中心',
    }
    return (
        <div className="main_top">
            {/* <div className="header_container">
                <Logo isSetting={props.isSetting ? true : false} />
                <div className="app_name">{props.title || '消息中心'}</div>
                <div className="header_btn">
                    <span className="btn_work" onClick={goHome}>返回办公平台</span>
                    <span className="slice_line"></span>
    
                    <div className="user_info" onClick={goPerson}>
                        <i className="user_avatar" style={{
                            backgroundImage: `url('${decodeURIComponent(userInfo.PhotoPath)}')`
                        }}></i>
                        <span className="user_name">{decodeURIComponent(userInfo.UserName)}</span>
                        {
                            currentIdentity?.isPreset == 'true' ?
                                <img className="user_image" src={currentIdentity.iconUrl} alt="头像" /> :
                                <span className="user_identity" style={{
                                    backgroundImage: `url('${currentIdentity?.iconUrl || currentIdentity?.identityImg}')`
                                }} title={currentIdentity?.identityName}>{currentIdentity?.identityName}</span>
                        }

                    </div>
                    <i className="quitlogo" onClick={quitMethod}></i>
                </div>
            </div> */}
            <LgTopBarContainer className={props.className}>
                <SystemInfo {...systemInfo}>
                </SystemInfo>
                <div style={{display:'flex',alignItems:'center'}}>
                    <BackToOfficialBlock handClick={goHome} />
                    <LgSplitLine margin={'0 10px'} />
                    <div onClick={goPerson}>
                        <UserBlock userImageUrl={userInfo.PhotoPath} userName={userInfo.UserName} />
                    </div>
                    {/* <UserBlock userImageUrl={userInfo.PhotoPath} userName={userInfo.UserName} /> */}
                    {/* {
                            currentIdentity?.isPreset == 'true' ?
                            <IdentityBlock identityImgUrl={currentIdentity?.iconUrl || currentIdentity?.identityImg}>
                        </IdentityBlock> :
                               <IdentityBlock identityImgUrl={currentIdentity?.iconUrl || currentIdentity?.identityImg}>
                               <span className={(classNames("define-identity"))}>自定义身份</span>
                           </IdentityBlock>
                        } */}
                    {/* <IdentityBlock identityImgUrl={currentIdentity?.iconUrl || currentIdentity?.identityImg}>
                        <span className={(classNames("define-identity"))}>自定义身份</span>
                    </IdentityBlock> */}

                    <IdentityBlock identityImgUrl={currentIdentity?.iconUrl || currentIdentity?.identityImg}>
                        {
                             currentIdentity.isPreset ?
                                <span className={(classNames("define-identity"))} title={currentIdentity.identityName} >
                                    {/* {currentIdentity.identityName.length > 4 ? currentIdentity.identityName.slice(0,4) + '...' : currentIdentity.identityName} */}
                                    </span>
                                : ''
                        }
                    </IdentityBlock>

                    <LogoutBlock handClick={quitMethod} />
                </div>
            </LgTopBarContainer>
        </div>
    )
}
const mapProps = (state) => {
    return {
        sysAddrInfo: state.sysAddrInfo,
        sysInfo: state.sysInfo,
        currentIdentity: state.currentIdentity,
        userInfo: state.userInfo,
        isEdu: state.isEdu
    }
}
export default connect(mapProps)(Header);

const Logo = styled.div`
    display: inline-block;
    vertical-align: top;
    width: 48px;
    height: 48px;
    margin-top: 14px;
    background-image:${(props) => props.isSetting ? `url(${MessageSetLogo})` : `url(${MessageLogo})`};
    background-size: 100% 100%;
 
`